package com.example.security.handler;

import com.example.security.entity.SysUser;
import com.example.security.service.SecurityService;
import com.example.security.util.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * SSO认证成功处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SsoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;
    private final SecurityService securityService;
    private final JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        
        try {
            SysUser user = (SysUser) authentication.getPrincipal();
            log.info("用户[{}]SSO登录成功", user.getUsername());

            // 生成token
            String token = jwtUtils.generateToken(user);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("data", new HashMap<String, String>() {{
                put("token", token);
                put("tokenType", "Bearer");
            }});

            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(result));
            
        } catch (Exception e) {
            log.error("SSO登录成功处理异常", e);
            throw new ServletException("SSO登录处理失败");
        }
    }
} 